/**
 * Copyright (C) 2012 The SkyTvOS Project
 * <p/>
 * Version     Date           Author
 * ─────────────────────────────────────
 * 2014-11-3         Root.Lu
 */

package com.coocaa.x.framework.data;

import android.os.Parcel;
import android.os.Parcelable;

import com.alibaba.fastjson.JSONObject;

public class JObject implements Parcelable {
    public static final String EMPTY_STRING = "";

    public JObject() {

    }

    public final String toJSONString() {
        Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
        return JSONObject.toJSONString(this);
    }

    @Override
    public String toString() {
        return toJSONString();
    }

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(toString());
    }

    public static <T> T parseJObject(String json, Class<T> clazz) {
        Thread.currentThread().setContextClassLoader(clazz.getClassLoader());
        return JSONObject.parseObject(json, clazz);
    }

    public static <T> Parcelable.Creator<T> createCREATOR(final Class<T> clazz,
                                                          Parcelable.Creator<T> c) {
        if (c != null)
            return c;
        return new Parcelable.Creator<T>() {
            @Override
            public T createFromParcel(Parcel source) {
                return JObject.parseJObject(source.readString(), clazz);
            }

            @Override
            public T[] newArray(int size) {
                return clazz.getEnumConstants();
            }
        };
    }

    public static final Parcelable.Creator<JObject> CREATOR = createCREATOR(JObject.class, null);
}
